package com.yswy.domain.common.util;

import com.alibaba.fastjson.JSONObject;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import com.yswy.domain.entity.IpPlace;

import java.util.ArrayList;
import java.util.List;

public class BaiduIpApi {
    private static String AccessKey= "1d06fddcd4eb48718030160720b7748b";
    private static String AppSecret= "7f3578f819c94d019b0d9996e5a7f3f9";
    private static String AppCode= "ee869ec36a7046899231b6dce8412330";
    public static IpPlace getIpPlace(String ip) {

        String path = "http://gwgp-uhhqextob4p.n.bdcloudapi.com/query/";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);
        request.setCredentials(AccessKey, AppSecret);
        request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");
        request.addQueryParameter("ip", ip);
//        {"ret":"ok","ip":"171.214.202.23","data":["中国","四川","成都","双流","电信","610200","028"]}
//        {"ret":"ok","ip":"120.239.64.197","data":["中国","广东","广州","海珠","移动","510200","020"]}
        //{"ret":"ok","ip":"114.139.71.248","data":["中国","贵州","遵义","播州","电信","562400","0859"]}

        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());
        try {
            ApiExplorerResponse response = client.sendRequest(request);
            // 返回结果格式为Json字符串
            JSONObject jsonObject = JSONObject.parseObject(response.getResult());
            if (jsonObject.getString("ret").equals("ok")){
                return new IpPlace(ip ,jsonObject.getString("data")  , null);
            }else {
                return new IpPlace(ip ,jsonObject.getString("data") );
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new IpPlace(ip ,"无效ip");
        }
    }

    public static void main(String[] args) {
        List<String> ss = new ArrayList<>();
        ss.add("175.24.88.78") ;
        ss.add("175.24.212.186") ;
        ss.add("81.68.167.172") ;
        for (String s:ss
             ) {
            IpPlace ipPlace =  getIpPlace(s);
            System.out.println(ipPlace.getPlaceDatas());
        }

    }
}
